package com.live.luowang.Fragment.Recommendation;

import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.google.gson.Gson;
import com.live.luowang.Function.HttpUrl;
import com.live.luowang.JsonData.MusictionInfoData;
import com.live.luowang.JsonData.MusitionData;
import com.live.luowang.MusicServie.MusicPlayingActivity;
import com.live.luowang.MusicServie.MusicProvider;
import com.live.luowang.MusicServie.MusicService;
import com.live.luowang.MyApplication;
import com.live.luowang.R;
import com.nostra13.universalimageloader.core.ImageLoader;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * Created by Chen on 2016/4/12.
 */
public class RecommendationFragment extends Fragment implements CompoundButton.OnCheckedChangeListener{
    @Bind(R.id.FRecommTopicImage)
    ImageView topicImage;
    @Bind(R.id.FRecommTitle)
    TextView title;
    @Bind(R.id.FRecommArtist)
    TextView artist;
    @Bind(R.id.FRecommContent)
    WebView content;
    @Bind(R.id.FRecommPlay)
    CheckBox recommPlay;
    private MusitionData.ListBean listBean;
    private MusictionInfoData musictionInfoData;
    private ImageView loading;
    private AnimationDrawable animationDrawable;
    private View myView = null;
    private WebChromeClient.CustomViewCallback myCallback = null;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_recommendation_layout, null);
        loading = (ImageView) view.findViewById(R.id.Loading);
        animationDrawable = (AnimationDrawable) loading.getDrawable();
        animationDrawable.start();
        ButterKnife.bind(this, view);
        if (getArguments() != null) {
            listBean = (MusitionData.ListBean) getArguments().get("data");
            getData(Integer.valueOf(listBean.getId()));
        }
        recommPlay.setOnCheckedChangeListener(this);
        topicImage.setFocusable(true);
        topicImage.setFocusableInTouchMode(true);
        topicImage.requestFocus();
        return view;
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (isChecked){
            MusicProvider.setRecommTracksList(musictionInfoData.getOther_tracks());
            Intent intent=new Intent(getActivity(), MusicService.class);
            intent.putExtra("click",true);
            intent.putExtra("type",1);
            getActivity().startService(intent);
            Intent intent1=new Intent(getActivity(), MusicPlayingActivity.class);
            getActivity().startActivity(intent1);
        }else {
            Intent intent=new Intent();
            intent.setAction("musicBarAction");
            intent.putExtra("action",1);
            getActivity().sendBroadcast(intent);
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    public static RecommendationFragment getInstance(MusitionData.ListBean listBean) {
        RecommendationFragment fragment = new RecommendationFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable("data", listBean);
        fragment.setArguments(bundle);
        return fragment;
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            try {
                ImageLoader.getInstance().displayImage(musictionInfoData.getCover_url(), topicImage);
            } catch (IllegalArgumentException e) {
                Log.e("error", "IllegalArgumentException");
            }
            animationDrawable.stop();
            loading.setVisibility(View.GONE);
            try {
                WebSettings settings = content.getSettings();
                settings.setDefaultTextEncodingName("UTF-8");
                settings.setLoadWithOverviewMode(true);
                settings.setUseWideViewPort(true);
                settings.setJavaScriptEnabled(true);
                settings.setAllowFileAccess(true);
                settings.setAppCacheEnabled(true);
                settings.setDatabaseEnabled(true);
                content.setWebChromeClient(new WebChromeClient() {
                    @Override
                    public void onShowCustomView(View view, CustomViewCallback callback) {
                        super.onShowCustomView(view, callback);
                        if (myCallback != null) {
                            myCallback.onCustomViewHidden();
                            myCallback = null;
                            return;
                        }
                        ViewGroup parent = (ViewGroup) content.getParent();
                        parent.removeView(content);
                        parent.addView(view);
                        myView = view;
                        myCallback = callback;
                    }

                    @Override
                    public void onHideCustomView() {
                        super.onHideCustomView();
                        if (myView != null) {

                            if (myCallback != null) {
                                myCallback.onCustomViewHidden();
                                myCallback = null;
                            }

                            ViewGroup parent = (ViewGroup) myView.getParent();
                            parent.removeView(myView);
                            parent.addView(content);
                            myView = null;
                        }
                    }
                });
                content.setWebChromeClient(new WebChromeClient() {
                    @Override
                    public void onShowCustomView(View view, CustomViewCallback callback) {
                    }
                });
                content.loadData(getHtmlData(musictionInfoData.getArticle().getContent()), "text/html; charset=UTF-8", null);
                title.setText(musictionInfoData.getTrack().getSonger());
                artist.setText(musictionInfoData.getDescription());
            } catch (NullPointerException e) {
                Log.e("error", "NullPointerException");
            }
        }
    };

    private void getData(int id) {
        String url = HttpUrl.MUSITIONINFO + String.valueOf(id);
        StringRequest request = new StringRequest(0, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                Gson gson = new Gson();
                response = response.substring(7);
                response = response.substring(0, response.length() - 1);
                musictionInfoData = gson.fromJson(response, MusictionInfoData.class);
                handler.sendEmptyMessage(1);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });
        MyApplication.getInstance().getQueue().add(request);
    }

    private String getHtmlData(String bodyHTML) {
        String head = "<head>" +
                "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, user-scalable=no\"> " +
                "<style>img{max-width: 100%; width:auto; height:auto;}" +
                "iframe{ width:100%; height:" + String.valueOf(cacu()) + ";}" +
                "span{font-size:10px;}" +
                "p span{font-size:14px; text-decoration:none;}" +
                "p{font-size:14px; line-height:170%;}" +
                "</style>" +
                "</head>";
        return "<html>" + head + "<body>" + bodyHTML + "</body></html>";
    }

    private double cacu() {
        double rate = getResources().getDisplayMetrics().widthPixels;
        rate = rate / 16 * 3;
        return rate;
    }
}
